using AutoTest.Core.Infrastructure.Messaging;

namespace AutoTest.Core.Domain.SnarlNotification
{
    public class SnarlNotifier : IConsumerOf<TestRunStartedMessage>, IConsumerOf<TestRunCompletedMessage>
    {
        public const string AutoTest = "AutoTest";
        public const string Info = "Info";
        public const string Pass = "Pass";
        public const string Fail = "Fail";

        private readonly ISnarl _snarl;
        private readonly IAutoTestConfiguration _configuration;

        public SnarlNotifier(ISnarl snarl, IAutoTestConfiguration configuration)
        {
            _snarl = snarl;
            _configuration = configuration;

            if (IsEnabled)
            {
                _snarl.Register(AutoTest);
                _snarl.AddClass(AutoTest, Info, Info);
                _snarl.AddClass(AutoTest, Pass, Pass);
                _snarl.AddClass(AutoTest, Fail, Fail);
            }
        }

        public void Consume(TestRunStartedMessage msg)
        {
            if (!IsEnabled)
                return;

            _snarl.Notify(AutoTest, Info, "", "Running tests...", 5);
        }

        public void Consume(TestRunCompletedMessage msg)
        {
            if (!IsEnabled)
                return;

            if (msg.Success)
            {
                _snarl.Notify("AutoTest.Net", "Pass", "Success", msg.NumberOfTestsRun + " tests run", 7);
            }
            else
            {
                if (msg.NumberOfTestsRun > 0)
                {
                    _snarl.Notify("AutoTest.Net", "Fail", msg.NumberOfFailures + " Failures", msg.FailureSummary.Replace("\r\n", "\n"), 30);
                }
                else
                {
                    _snarl.Notify("AutoTest.Net", "Fail", "Build failed", "0 tests run", 7);
                }
            }
        }

        private bool IsEnabled
        {
            get { return _configuration.SendNotificationsToSnarl; }
        }
    }
}